<template>
<div class="dialog">
    <div class="loginPage">
        <h1 class="title">{{$t('message.loginPage')}}</h1>
        <el-form class="form" :model="authInfo" ref="authInfo" :rules="rules" >
            <el-form-item prop="username">
                <el-input type="text" v-model="authInfo.username" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item prop="password" class="el-pwd" @keyup.enter.native="onEnterUp" v-on:click.native="onFocus">
                <el-input id="pwd" class="inputPwd" type="password" v-model="authInfo.password" @keyup.enter.native="onEnterUp" v-on:click.native="onFocus" placeholder="密码" >
                  </el-input>                
            </el-form-item>
							<el-form-item>								
            <el-button class="btn" type="primary" @click="Login" :loading="logining">{{$t('message.login')}}</el-button>
							</el-form-item>
						<el-checkbox  class="remember" v-model="authInfo.remember" @change="onRememberChange">{{$t('message.rememberpwd')}}</el-checkbox>
        </el-form>              
    </div>
</div>
</template>

<script>
import { getHostName, api } from "../../../libs/api";
import { mapState } from "vuex";
var nuid = require("nuid");
import md5 from "js-md5";
import ebus from "../../../libs/ebus.js";
export default {
  created() {
    this.loadClientId();
    this.loadAuthInfo();
  },
  data() {
    return {
      clientId: '',
      authInfo: {
        username: "",
        password: "",
        remember: true
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名" },
          { min: 1, max: 32, message: "长度在32个字符内" }
        ],
        password: [{ required: true, message: "请输入密码" }]
      },
      logining: false
    };
  },
  methods: {
    Login() {
      if (!this.authInfo.username || !this.authInfo.password) {
        return;
      }
      this.$refs.authInfo.validate(valid => {
        if (!valid) {
          return;
        }
      });
      api.DisConnect();

      this.conn = api.CreatConnect({
        reconnect: false,
        url: getHostName()
      });

      var option = {
        clientId: this.clientId,
        username: this.authInfo.username,
        force: true
      };
      if (this.authInfo.password.substring(0, 4) === "md5#") {
        option.password = this.authInfo.password;
      } else {
        option.password = "md5#" + md5(this.authInfo.password);
      }
      option = JSON.stringify(option);

      this.logining = true;
      var url = "$method.login.auth.cmd";
      api.onRequest(url, option, null, this.clientId, (msg, reply) =>{        
      }).then(
        msg => {
          this.logining = false;
          var res = JSON.parse(msg);
          if (res.code == 0) {
            if(this.authInfo.remember){
              this.saveAuthInfo();
            } else{
              this.clearAuthInfo();
            }
            
            api.onRequest("$method.getJwt.auth.cmd", null, null, null, function(msg1, reply1){
              var resData = JSON.parse(msg1);
                if (resData.code == 0) {
                  this.$store.dispatch("system/getJWT", resData.data.jwt);
                }
            }.bind(this))
            this.saveClientId();
            ebus.emit("getCCInfo", this);//先确定要不要显示中控模块主菜单
            ebus.emit("getProductInfo", this);
            this.$store.dispatch("system/setAuthInfo", this.authInfo);
            setTimeout(() => {
              this.$router.push("/system");
            }, 100)
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
        },
        err => {
          this.logining = false;
        }
      );
    },
    onEnterUp() {
      this.Login();
    },
    onRememberChange(val){      
      if(!val){
        this.clearAuthInfo()
      }
    },
    clearAuthInfo() {
       if (localStorage) {
        localStorage.clear()
      }
    },
    saveClientId(){
      if (localStorage) {
        localStorage.setItem("clientId", this.clientId);
      }
    },
    loadClientId(){
      if (localStorage) {
        let clientId = localStorage.getItem("clientId");
        if (clientId) {
          this.clientId = clientId;
        } else{
          this.clientId = nuid.next();
        }
      } else{
        this.clientId = nuid.next();
      }
    },
    saveAuthInfo() {
      var authInfo = {};
      authInfo["a" + md5("username")] = this.authInfo.username;
      authInfo["c" + md5("remember")] = this.authInfo.remember;
      if (this.authInfo.password.substring(0, 4) == "md5#") {
        authInfo["b" + md5("password")] = this.authInfo.password;
      } else {
        authInfo["b" + md5("password")] = "md5#" + md5(this.authInfo.password);
      }
      if (localStorage) {
        localStorage.setItem("a" + md5("authInfo"), JSON.stringify(authInfo));
      }
    },
    loadAuthInfo() {
      if (localStorage) {
        let authInfo = JSON.parse(localStorage.getItem("a" + md5("authInfo")));
        if (authInfo) {
          if (!authInfo["c" + md5("remember")]) {
            localStorage.clear();
            this.authInfo.username = "";
            this.authInfo.password = "";
            this.authInfo.remember = false;
          } else {
            this.authInfo.username = authInfo["a" + md5("username")];
            this.authInfo.password = authInfo["b" + md5("password")];
            this.authInfo.remember = authInfo["c" + md5("remember")];
          }
        }
      }
    },
    onFocus() {      
      var pwd = document.getElementById('pwd')
      pwd.blur();
      pwd.focus();
      if (typeof pwd.selectionStart == "number") {
          pwd.selectionStart = pwd.selectionEnd = pwd.value.length;
      } else if (typeof el.createTextRange != "undefined") {
          pwd.focus();
          var range = pwd.createTextRange();
          range.collapse(false);
          range.select();
      }
      // pwd.value = pwd.value
    }
  }
};
</script>

<style >

.dialog {
  width: 100%;
  height: 100%;
  background: #324057;
}
.loginPage {
  width: 320px;
  height: 210px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -105px;
  margin-left: -160px;
  padding: 25px;
  border-radius: 5px;
  text-align: center;
  background-color: #fff;
}
.loginPage p {
  color: red;
  text-align: left;
}
.form {
  background-color: #ffffff;
}
.title {
  position: absolute;
  width: 100%;
  top: -100px;
  left: 0;
  color: #fff;
}
.el-form-item {
  margin-bottom: 22px;
}
.btn {
  width: 320px;
  font-size: 14px;
}
.remember {
  font-size: 14px;
}
.inputPwd .el-input__inner{
  padding-right: 224px;
}
</style>